package com.aizuda.security.example.controller;

import com.aizuda.security.annotation.RestEncrypt;
import com.aizuda.security.autoconfigure.SecurityProperties;
import com.aizuda.security.example.entity.LoginParam;
import com.aizuda.security.example.entity.User;
import com.aizuda.security.toolkit.JacksonUtils;
import com.baomidou.kisso.common.encrypt.RSA;
import lombok.AllArgsConstructor;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

/**
 * 测试文件 resources/ApiTest.http
 * <p>
 * 尊重知识产权，CV 请保留版权，爱组搭 http://aizuda.com 出品
 */
@RestController
@AllArgsConstructor
public class SecurityController {
    private SecurityProperties securityProperties;

    /**
     * 测试 rsa + base64 加密字符串 http://localhost:8080
     */
    @GetMapping
    public String testRsaBase64() throws Exception {
        LoginParam loginParam = new LoginParam();
        loginParam.setUsername("admin");
        loginParam.setPassword("123456");
        return Base64.encodeBase64String(RSA.encryptByPublicKey(JacksonUtils.toJSONString(loginParam)
                .getBytes(StandardCharsets.UTF_8), securityProperties.getPublicKey()));
    }

    /**
     * 测试 get 请求，注意！！地址参数不处理加密逻辑
     * <p>
     * 响应结果会加密
     * <p>
     * http://localhost:8080/testGet?username=admin&password=123456
     */
    @RestEncrypt
    @GetMapping("/testGet")
    public User testGet(LoginParam loginParam) {
        return User.newUser(loginParam);
    }

    /**
     * 测试 post 普通表单请求，注意！！这里参数也不会解密处理
     */
    @RestEncrypt
    @PostMapping("/testPost")
    public User testPost(LoginParam loginParam) {
        return User.newUser(loginParam);
    }

    /**
     * 测试 post json 解密请求，加密响应数据
     */
    @RestEncrypt
    @PostMapping("/testJson")
    public User testJson(@RequestBody LoginParam loginParam) {
        System.out.println("解密内容 = " + JacksonUtils.toJSONString(loginParam));
        return User.newUser(loginParam);
    }

    /**
     * 测试 post json 请求
     * 注意！！当前注解申明 json 入参为明文不需要解密逻辑，默认处理加密响应数据
     */
    @RestEncrypt(decrypt = false)
    @PostMapping("/testJsonNonDecrypt")
    public User testJsonNonDecrypt(@RequestBody LoginParam loginParam) {
        return User.newUser(loginParam);
    }

    /**
     * 测试 post json 解密请求，不加密响应数据
     */
    @RestEncrypt(encrypt = false)
    @PostMapping("/testJsonNonEncrypt")
    public User testJsonNonEncrypt(@RequestBody LoginParam loginParam) {
        System.out.println("解密内容 = " + JacksonUtils.toJSONString(loginParam));
        return User.newUser(loginParam);
    }
}
